#include "gamebody.hpp"

Creature* target = new Creature(Names::CREATURE_WOOD_TARGET);

Weapon* sword = new Weapon(Names::SWORD);

LayerModel* layer1 = new LayerModel(80, 40);

GameBody::GameBody(string title, int width, int height){
    srandom(time(nullptr));

    SDL_Init(SDL_INIT_EVERYTHING);
    IMG_Init(IMG_INIT_JPG|IMG_INIT_PNG|IMG_INIT_TIF);
    TTF_Init();
    
    SDL_Log("init all");

    window = SDL_CreateWindow(title.c_str(), SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, width, height, SDL_WINDOW_SHOWN|SDL_WINDOW_RESIZABLE);
    assert(window!=nullptr);

    SDL_Log("Created Window");

    render = SDL_CreateRenderer(window, -1, 0);
    assert(render!=nullptr);

    SDL_Log("Created Render");
    
    canva = SDL_CreateTexture(render, SDL_PIXELFORMAT_RGBA8888, SDL_TEXTUREACCESS_TARGET, width, height);
    assert(canva!=nullptr);
    SDL_SetRenderTarget(render, canva);

    SDL_Log("Created Canva");

    SDL_Log("Window size (%d, %d)", CANVA_WIDTH, CANVA_HEIGHT);
    SDL_Log("Game gride size (%d, %d)", GRID_COL, GRID_ROW);

    InitTextResources();

    SDL_Log("Init text resources");

    charset = new CurseSheet;

    SDL_Log("Init charset");

    _controller = &GamingController::GetInstance();

    SDL_Log("Welcome rougelike game version %s", version);

    // NOTE init some demo object
    worldmodel.RegistLayer(layer1);
    worldmodel.ChangeLayer(layer1);

    buildRoom(10, 10, 10, 15);
    player->SetPosition(12, 12);
    player->SetColor({0, 255, 0});
    player->properties_.Set(50, 40, 10, 20, 100, 7, 18, 12, 12, 12, 320);
    target->SetPosition(14, 14);
    target->SetColor({100, 0, 100});
    target->properties_.Set(50, 40, 10, 10, 100, 10, 10, 10, 10, 10, 10);
    sword->SetPosition(13, 13);
    sword->SetColor({0, 0, 255});

    //Add demo to layer
    layer1->AddObject(player);
    layer1->AddObject(target);
    layer1->AddObject(sword);

    //Add demo to World
    worldmodel.RegistObject(player);
    worldmodel.RegistObject(target);
    worldmodel.RegistObject(sword);

    diary.AddText("Hello world");
    diary.AddText("Welcome to the rougelike");
}

void GameBody::Run(){
    while(!isquit){
        SDL_SetRenderDrawColor(render, 100, 100, 100, 255);
        SDL_RenderClear(render);
        eventHandle();
        step();
        SDL_Delay(30);
        SDL_SetRenderTarget(render, nullptr);
        SDL_RenderCopy(render, canva, nullptr, nullptr);
        SDL_RenderPresent(render);
        SDL_SetRenderTarget(render, canva);
    }
}

void GameBody::eventHandle(){
    while(SDL_PollEvent(&_event)){
        if(_event.type==SDL_QUIT)
            isquit = true;
        _controller->Control(_event, *player);
    }
}

GameBody::~GameBody(){
    if(canva)
        SDL_DestroyTexture(canva);
    delete charset;
    ReleaseTextResources();
    TTF_Quit();
    IMG_Quit();
    SDL_Quit();
}

void GameBody::step(){
    worldmodel.Update();
    worldmodel.Draw();
    diary.Draw(0, 0);
    DrawPlayerInfo();
}
